package com.hd.hdxgddcommon.custom;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpRequest;
import org.apache.http.NoHttpResponseException;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.protocol.HttpContext;

import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.UnknownHostException;

/**
 * Created by Administrator on 2019/3/26.
 */
@Slf4j
public class CallbackHttpRequestRetryHandler implements HttpRequestRetryHandler {

    @Override
    public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
        if (executionCount > 1) {
            //重试超过1次,放弃请求
            log.error("retry has more than 1 time, give up request");
            return false;
        }
        if (exception instanceof NoHttpResponseException) {
            //服务器没有响应,可能是服务器断开了连接,应该重试
            log.error("receive no response from server, retry");
            return true;
        }
        if (exception instanceof SSLHandshakeException) {
            // SSL握手异常
            log.error("SSL hand shake exception");
            return false;
        }
        if (exception instanceof InterruptedIOException) {
            //超时
            log.error("InterruptedIOException");
            return false;
        }
        if (exception instanceof UnknownHostException) {
            // 服务器不可达
            log.error("server host unknown");
            return false;
        }
        if (exception instanceof ConnectTimeoutException) {
            // 连接超时
            log.error("Connection Time out");
            return false;
        }
        if (exception instanceof SSLException) {
            log.error("SSLException");
            return false;
        }

        HttpClientContext httpClientContext = HttpClientContext.adapt(context);
        HttpRequest request = httpClientContext.getRequest();
        if (!(request instanceof HttpEntityEnclosingRequest)) {
            //如果请求不是关闭连接的请求
            return true;
        }
        return false;
    }
}
